window.onload = function () {
    InitTimeDisplay();
    let init = GetParams("init");
    switch (init) {
        case "get":
            document.getElementById("float-add-button").style.display = "none";
            ShowGetInfoDialogOverlay();
            break;
        case "show":
            document.getElementById("float-add-button").style.display = "none";
            let tableName = GetParams("tableName");
            let rowKey = GetParams("rowKey");
            Get(tableName, rowKey);
            break;
        case "new":
        default:
            document.getElementById("float-add-button").click();
            break;
    }
}

function AddColumn() {
    let columnButtonBox = event.currentTarget.parentNode;
    let rowBox = columnButtonBox.parentNode;
    let newColumn = document.createElement("div");
    newColumn.setAttribute("class", "column-box");
    newColumn.innerHTML = `
        <label class="input-label">列名: </label>
        <input placeholder="列" class="column-input" autocomplete="off">
        <span> </span>
        <label class="input-label">内容: </label>
        <input placeholder="值" class="column-value-input" autocomplete="off">
<!--        <input class="can-search" type="checkbox" onchange="SearchCheckboxClicked()">-->
<!--        <span class="can-search-checkmark"></span>-->
<!--        <input class="can-cut" type="checkbox">-->
<!--        <span class="can-cut-checkmark"></span>-->
        <button class="column-del" onclick="DelColumn()"></button>`;
    rowBox.insertBefore(newColumn, columnButtonBox);
}

function CheckIfCanEbbColumn(rowBox)
{
    let columnBoxes = rowBox.getElementsByClassName("column-box");
    if (rowBox.getAttribute("remote-flag"))
        return columnBoxes.length > 0;
    return columnBoxes.length > 1;
}

function DelColumn() {
    let columnBox = event.currentTarget.parentNode;
    let rowBox = columnBox.parentNode;
    if (!CheckIfCanEbbColumn(rowBox))
        return;
    rowBox.removeChild(columnBox);
}

function EbbColumn() {
    let rowBox = event.currentTarget.parentNode.parentNode;
    if (!CheckIfCanEbbColumn(rowBox))
        return;
    let columnBoxes = rowBox.getElementsByClassName("column-box");
    rowBox.removeChild(columnBoxes[columnBoxes.length - 1]);
}

function AddRow() {
    let contentBox = document.getElementsByClassName("content-box")[0];
    let newRow = document.createElement("div");
    newRow.setAttribute("class", "row-box");
    newRow.innerHTML = `
        <div class="row-key">
            <label class="input-label">行名: </label>
            <input placeholder="行键" class="row-key-input" autocomplete="off">
            <button class="row-key-del" onclick="DelRow()"></button>
        </div>
        <div class="column-button-box">
            <button class="add-button" onclick="AddColumn()">+</button>
            <button class="ebb-button" onclick="EbbColumn()">-</button>
        </div>`;
    contentBox.appendChild(newRow);
    newRow.lastElementChild.firstElementChild.click();
}

function DelRow() {
    let es = document.getElementsByClassName("row-box");
    if (es.length < 2)
        return;
    let rowBox = event.currentTarget.parentNode.parentNode;
    let contentBox = rowBox.parentNode;
    contentBox.removeChild(rowBox);
}

function ShowGetInfoDialogOverlay() {
    let mask = document.getElementById("data-get-dialog");
    mask.style.display = "block";
    document.documentElement.style.overflow = "hidden";
}

function CloseGetInfoDialog() {
    let mask = document.getElementById("data-get-dialog");
    mask.style.display = "none";
    document.documentElement.style.overflow = "auto";
}


function SearchCheckboxClicked() {
    let canCut = event.currentTarget.parentNode.getElementsByClassName("can-cut")[0];
    let canCutCheckmark = event.currentTarget.parentNode.getElementsByClassName("can-cut-checkmark")[0];
    if (event.currentTarget.checked) {
        canCut.checked = true;
        canCut.disabled = true;
        canCutCheckmark.style.opacity = "0.5";
    } else {
        canCut.disabled = false;
        canCutCheckmark.style.opacity = "1";
    }
}

function OnGetInfoButtonClicked() {
    let inputs = event.currentTarget.parentNode.getElementsByClassName("data-get-dialog-window-content")[0].getElementsByClassName("input");
    let tableName = inputs[0].value;
    let rowKey = inputs[1].value;
    if (tableName === "") {
        ShowAlertOverlay("表名不能为空");
        return;
    }
    if (rowKey === "") {
        ShowAlertOverlay("行键不能为空");
        return;
    }
    Get(tableName, rowKey);
}

function Get(tableName, rowKey) {
    let url = baseUrl + "/manage/" + tableName + "/" + rowKey;
    let http = new XMLHttpRequest();
    http.open("GET", url);
    http.send();
    http.onreadystatechange = function () {
        if (this.readyState === http.DONE) {
            let resJson = JSON.parse(this.responseText);
            let displayText = "";
            switch (this.status) {
                case 0:
                    ShowAlertOverlay("无法连接到远端服务器!");
                    CloseLoadingOverlay();
                    break;
                case 200:
                    console.log(resJson);
                    let tableNameInput = document.getElementById("tableNameInput");
                    tableNameInput.value = tableName;
                    tableNameInput.disabled = true;

                    let contentBox = document.getElementsByClassName("content-box")[0];
                    let newRow = document.createElement("div");
                    newRow.setAttribute("class", "row-box");
                    newRow.setAttribute("remote-flag", "true");
                    newRow.innerHTML = `
                        <div class="row-key">
                            <label class="input-label">行名: </label>
                            <input placeholder="行键" class="row-key-input" autocomplete="off" disabled="true" value="`+ rowKey +`">
<!--                            <button class="row-key-del" onclick="DelRow()"></button>-->
                        </div>
                        <div class="column-button-box">
                            <button class="add-button" onclick="AddColumn()">+</button>
                            <button class="ebb-button" onclick="EbbColumn()">-</button>
                        </div>`;
                    let cells = resJson["Result"]["cells"];
                    for (let i = 0; i < cells.length; i++)
                    {
                        let cell = cells[i];
                        let columnButtonBox = newRow.getElementsByClassName("column-button-box")[0];
                        let newColumn = document.createElement("div");
                        newColumn.setAttribute("class", "column-box-remote");
                        newColumn.innerHTML = `
                            <label class="input-label">列名: </label>
                            <input placeholder="列" class="column-input" autocomplete="off" value="`+ cell.column + `">
                            <span> </span>
                            <label class="input-label">内容: </label>
                            <input placeholder="值" class="column-value-input" autocomplete="off" value="` + cell.value + `">
<!--                            <input class="can-search" type="checkbox" onchange="SearchCheckboxClicked()">-->
<!--                            <span class="can-search-checkmark"></span>-->
<!--                            <input class="can-cut" type="checkbox">-->
<!--                            <span class="can-cut-checkmark"></span>-->
<!--                            <button class="column-del" onclick="DelColumn()"></button>-->`;
                        newRow.insertBefore(newColumn, columnButtonBox);
                    }
                    contentBox.appendChild(newRow);

                    if (resJson.Warning.length !== 0) {
                        for (let i = 0; i < resJson.Warning.length; i++) {
                            displayText += resJson.Warning[i];
                            displayText += "<br/>";
                        }
                        ShowAlertOverlay(displayText);
                    }
                    CloseGetInfoDialog();
                    CloseLoadingOverlay();
                    break;
                default:
                    displayText += "Code: ";
                    displayText += this.status;
                    displayText += " ";
                    displayText += this.statusText;
                    displayText += "<br/>";
                    for (let i = 0; i < resJson.Warning.length; i++) {
                        displayText += resJson.Warning[i];
                        displayText += "<br/>";
                    }
                    displayText += resJson.Error;
                    displayText += "<br/>";
                    ShowAlertOverlay(displayText);
                    CloseLoadingOverlay();
                    break;
            }
        }
    };
    ShowLoadingOverlay();
}

function Push() {
    let data =
        {
            tableName: "",
            rows: []
        };
    data.tableName = document.getElementById("tableNameInput").value;
    if (data.tableName === "") {
        ShowAlertOverlay("表名不能为空");
        return;
    }
    let rows = document.getElementsByClassName("row-box");

    for (let i = 0; i < rows.length; i++) {
        let rowObject = rows[i];
        let row =
            {
                rowKey: "",
                columns: []
            };
        row.rowKey = rowObject.getElementsByClassName("row-key")[0].getElementsByClassName("row-key-input")[0].value;
        if (row.rowKey === "") {
            ShowAlertOverlay("行键不能为空");
            return;
        }
        let columns = rowObject.getElementsByClassName("column-box");
        for (let j = 0; j < columns.length; j++) {
            let columnObject = columns[j];
            let column =
                {
                    column: "",
                    value: "",
                    canSearch: false,
                    canCut: false
                };
            column.column = columnObject.getElementsByClassName("column-input")[0].value;
            column.value = columnObject.getElementsByClassName("column-value-input")[0].value;
            column.canSearch = true;
            column.canCut = true;
            // column.canSearch = !columnObject.getElementsByClassName("can-search")[0].checked;
            // column.canCut = !columnObject.getElementsByClassName("can-cut")[0].checked;
            if (column.column === "") {
                ShowAlertOverlay("列名不能为空");
                return;
            }
            if (column.value === "") {
                ShowAlertOverlay("值不能为空");
                return;
            }
            row.columns.push(column);
        }
        data.rows.push(row);
    }
    let url = baseUrl + "/manage/" + data.tableName;
    let dataBody = JSON.stringify(data);
    let http = new XMLHttpRequest();
    http.open("PUT", url);
    http.send(dataBody);
    http.onreadystatechange = function () {
        if (this.readyState === http.DONE) {
            console.log(this.responseText);
            let resJson = JSON.parse(this.responseText);
            let displayText = "";
            switch (this.status) {
                case 0:
                    ShowAlertOverlay("无法连接到远端服务器!");
                    CloseLoadingOverlay();
                    break;
                case 200:
                    if (resJson.Warning.length !== 0) {
                        for (let i = 0; i < resJson.Warning.length; i++) {
                            displayText += resJson.Warning[i];
                            displayText += "<br/>";
                        }
                        ShowAlertOverlay(displayText);
                    }
                    else {
                        ShowOkOverlay();
                    }
                    CloseLoadingOverlay();
                    break;
                default:
                    displayText += "Code: ";
                    displayText += this.status;
                    displayText += " ";
                    displayText += this.statusText;
                    displayText += "<br/>";
                    for (let i = 0; i < resJson.Warning.length; i++) {
                        displayText += resJson.Warning[i];
                        displayText += "<br/>";
                    }
                    displayText += resJson.Error;
                    displayText += "<br/>";
                    ShowAlertOverlay(displayText);
                    CloseLoadingOverlay();
                    break;
            }
        }
    };
    ShowLoadingOverlay();
}

function test() {
    Push()
}